//
//  GSAppUIOrderView.m
//  GameSky
//
//  Created by lanou on 16/1/13.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSAppUIOrderView.h"
#import "GSOrderButton.h"

#define KBase_tag     100

@implementation GSAppUIOrderView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 夜间模式
//        self.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
        
        [self addSubViews];
    }
    return self;
}

- (void)addSubViews
{
    
    self.bgScrollView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    
    [self addSubview:self.bgScrollView];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
    
    [self.bgScrollView addGestureRecognizer:tap];
    
    self.bgScrollView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.35];
    
    
    
    self.contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight * 0.4)];
    
    self.contentView.backgroundColor = kRGBColor(0.94, 0.94, 0.94);
    
    [self.bgScrollView addSubview:self.contentView];
    
    
    
    
    self.tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 160, kScreenWidth, 70)];
    
    self.tipLabel.textAlignment = NSTextAlignmentCenter;
    
    self.tipLabel.text = @"拖动调整栏目顺序";
    
    [self.bgScrollView addSubview:self.tipLabel];
    
    
    self.buttonArray = [NSMutableArray array];
    
    self.buttonTitle = [NSMutableArray array];
    
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    
    // 一共10个按钮
    self.totalNumber = 10;
    
    /**
     *  创建9宫格
     */
    
    // 按钮的宽度
    CGFloat btW = (kScreenWidth - 25 * 2 - 15 * 3) / 4;
    CGFloat btH = 38;
    
    for (NSInteger i = 0; i < self.totalNumber; i++) {
        
        UIButton *bt = [UIButton buttonWithType:(UIButtonTypeCustom)];
        
        bt.frame = CGRectMake(20 + (btW + 15) * (i % 4), 15 + (btH + 15) * (i / 4), btW, btH);
        
        bt.backgroundColor = [UIColor redColor];
        
        bt.tag = KBase_tag + i;
        
        [bt setTitle:[NSString stringWithFormat:@"%@",self.titleListArray[i]] forState:(UIControlStateNormal)];
        
        
        
        /**
         *  添加点击删除方法
         */
        //        [bt addTarget:self action:@selector(doDelete:) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.contentView addSubview:bt];
        
        /**
         *  长按手势
         */
        
        if (![bt.titleLabel.text isEqualToString:@"头条"]) {
            
            UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
            
            [bt addGestureRecognizer:longPress];
            
            [self.buttonArray addObject:bt];

        }
    }

}

- (void)tapClick:(UITapGestureRecognizer *)recognizer
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(GSAppUIOrderViewTapClick:)]) {
        
        [self.delegate GSAppUIOrderViewTapClick:self];
        
    }
    
}

/**
 * 长按手势
 */
- (void)longPress:(UILongPressGestureRecognizer *)recognizer{
    
    // 取出当前长按的是哪个按钮
    UIButton *recognizerView = (UIButton *)recognizer.view;
    
    /**
     *  禁用其他按钮的拖拽手势
     */
    // 遍历这个视图上的所有按钮
    for (UIButton *bt in self.contentView.subviews) {
        // 如果按钮不是当前长按的按钮
        if (bt != recognizerView) {
            // 禁止不是当前长按按钮的交互
            bt.userInteractionEnabled = NO;
            
        }
    }
    
    
    // 长按视图在父视图的位置 (也就是触摸点的位置)
    CGPoint recognizerPoint = [recognizer locationInView:self.contentView];
    
    // 如果当前的手势状态是开始状态
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        
        // 开始 改变拖动的view的外观(放大,改变颜色等)
        // 通过动画完成
        [UIView animateWithDuration:0.2 animations:^{
            
            // 放大1.3倍
            recognizerView.transform = CGAffineTransformMakeScale(1.3, 1.3);
            
            // 透明度变为0.7
            recognizerView.alpha = 0.7;
            
        }];
        
        // 把拖动的view放大最上层
        [self bringSubviewToFront:recognizerView];
        
        // valuePoint 保存最新的移动位置
        
        self.valuePoint = recognizerView.center;
        
    }else if (recognizer.state == UIGestureRecognizerStateChanged){
        /**
         *  手势状态改变
         */
        
        // 更新当前长按按钮的位置
        recognizerView.center = recognizerPoint;
        
        // 遍历视图上的所有按钮
        for (UIButton *bt in self.buttonArray) {
            
            // 如果当前拖拽的按钮的中心点,被一个按钮的Frame所包含,并且这个按钮还不是当前拖拽按钮
            // 说明要改变位置了(两个按钮交换)
            if (CGRectContainsPoint(bt.frame, recognizerView.center) && bt != recognizerView) {
                
                // 开始位置
                NSInteger fromIndex = recognizerView.tag - KBase_tag;
                
                if (!self.beginIndex) {
                    
                    self.beginIndex = fromIndex;
                    
                }
                
                // 需要移动到的位置
                NSInteger toIndex = bt.tag - KBase_tag;
                
                self.endIndex = toIndex;
                
                // 如果移动到的位置大于开始位置, 则往后移动
                if ((toIndex- fromIndex) > 0) {
                    
                    /**
                     *  从开始位置 移动到结束位置
                     就是把开始的位置center变成结束位置的center
                     而结束位置的center变成开始位置的center
                     当然,如果前后之间有很多的按钮的话,则不断的前后互换
                     这样就完成了前后位置的互换
                     
                     */
                    
                    [UIView animateWithDuration:0.2 animations:^{
                        
                        // 循环,从当前位置的下一个开始
                        for (NSInteger i = fromIndex + 1; i <= toIndex; i++) {
                            
                            // 用tag值取出后面的button
                            _nextBt = [self.contentView viewWithTag:KBase_tag + i];
                            
                            // 记录后一个的button的中心点
                            self.nextPoint = _nextBt.center;
                            
                            // 将拖拽按钮的中心点给后一个button的中心点
                            _nextBt.center = self.valuePoint;
                            
                            // 而后一个按钮的中心点在赋给退拽的按钮
                            self.valuePoint = self.nextPoint;
                            
                            // 由于后一个按钮往前移动一个了,所以它的tag值要本能的减去1
                            _nextBt.tag--;
                            
                        }
                    
                        
                        
                        // 往后移动之后,把最后的位置的tag值赋值个当前长按的按钮
                        recognizerView.tag = KBase_tag + toIndex;
                        
                        self.endIndex = toIndex;
                        
                    }];

                    
                }else{
                    
                    // 往前移动
                    [UIView animateWithDuration:0.2 animations:^{
                        
                        for (NSInteger i = fromIndex - 1; i >= toIndex; i--) {
                            
                            _nextBt = (UIButton *)[self.contentView viewWithTag:i + KBase_tag];
                            
                            self.nextPoint = _nextBt.center;
                            
                            _nextBt.center = self.valuePoint;
                            
                            self.valuePoint = self.nextPoint;
                            
                            _nextBt.tag++;
    
                        }
                        // 把移动的最后的位置的tag值从新赋给当前退拽的按钮
                        recognizerView.tag = KBase_tag + toIndex;
                        
                        self.endIndex = toIndex;
                        
                    }];
                    
                }
                
            }
        }
        /**
         *  如果手势状态结束
         */
    }else if (recognizer.state == UIGestureRecognizerStateEnded){
        
        // 恢复其他按钮的交互
        for (UIButton *bt in self.buttonArray) {
            
            if (bt != recognizerView) {
                
                bt.userInteractionEnabled = YES;
                
            }
            
        }
        
        // 结束时候,恢复view的外观
        [UIView animateWithDuration:0.2 animations:^{
            
            recognizerView.transform = CGAffineTransformMakeScale(1.0, 1.0);
            
            recognizerView.alpha = 1.0;
            
            // 改变位置
            recognizerView.center = self.valuePoint;
        }];
        
        // 取出手指一直按住的那个按钮
        if (self.beginIndex == 0) {
            
            return;
        }
        UIButton *fromButton = self.buttonArray[self.beginIndex - 1];
        
        // 从数组中删除这个按钮
        [self.buttonArray removeObject:fromButton];
        
        // 再将它插入到要交换的目标处,这样,数组中的button的顺序就交换了
        [self.buttonArray insertObject:fromButton atIndex:self.endIndex - 1];
        
        // 交换完之后,清零,准备下次接收
        self.beginIndex = 0;
        
         // 交换完之后,清零,准备下次接收
        self.endIndex = 0;
        
        // 注意,这儿只能遍历按钮数组,不能变量subviews,subview上的按钮顺序不会变的
        for (UIButton *bt in self.buttonArray) {
            
            [self.buttonTitle addObject:bt.titleLabel.text];
        }
        
        // 再将头条插回第0处
        [self.buttonTitle insertObject:@"头条" atIndex:0];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(GSAppUIOrderViewButtonTitle:)]) {
            
            [self.delegate GSAppUIOrderViewButtonTitle:self.buttonTitle];
            
            // 在代理传值传出去之后,将存放button标题的数组清空,方便下一次存放
            [self.buttonTitle removeAllObjects];
            
        }
        
    }
    
}
@end
